import {RcFile} from "antd/es/upload";
import {globalApi} from "@/services/admin-api/globalApi";
import {message} from "antd";

const OSS = require('ali-oss');

let time: Date
let store: any

const loadConfig = async () => {
  const config = await globalApi('/aliyun/sts/get', {})

  console.log('config = ', config)
  time = new Date(config.data.expiration)
  console.log('time = ', time)

  store = new OSS({
    region: 'oss-cn-shenzhen',
    accessKeyId: config.data.accessKeyId,
    accessKeySecret: config.data.accessKeySecret,
    bucket: 'bdq-cloud',
    stsToken: config.data.securityToken
  });
}

const dateTimePath = () => {
  const date = new Date()
  return `/${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
}

// 身份证人像面
export const worker_id_card_front_url = 0
// 身份证国徽面
export const worker_id_card_back_url = 1
// 工作人员头像
export const worker_head_img_url = 2
// 工作人员健康证
export const worker_health_certificate_url = 3
export const product_banner = 4
export const product_detail = 5
export const product_main = 6

export const typePath: any = {
  [worker_id_card_front_url]: 'workerIdCardFront',
  [worker_id_card_back_url]: 'workerIdCardBack',
  [worker_head_img_url]: 'workerHeadImg',
  [worker_health_certificate_url]: 'workerHealthCertificate',
  [product_banner]: 'product_banner',
  [product_detail]: 'product_detail',
  [product_main]: 'product_main',
}

export async function aliyunUploadFile(file: RcFile, objId?: number, objIdStr?: string, objType?: any) {
  const hide = message.loading('正在上传')
  console.log('file = ', file)

  if (!time || time.getTime() + 10 * 1000 > new Date().getTime()) {
    await loadConfig()
  }

  const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
  const fileName = crypto.randomUUID().replaceAll('-', '') + "." + fileSuffix
  const filePath = '/' + typePath[objType] + dateTimePath() + '/' + fileName
  await globalApi("/attachment/upload", {
    fileOriginalName: file.name,
    fileSuffix: fileSuffix,
    fileName: fileName,
    filePath: filePath,
    fileSize: file.size,
    fileType: file.type,
    objType: objType,
    objId: objId,
    objIdStr: objIdStr,
  })
  await store.put(filePath, file)
  hide()
}

